import { createRouter, createWebHistory } from 'vue-router'
import { showToast } from 'vant'

const routes = [
  {
    path: '/',
    redirect: '/splash'
  },
  {
    path: '/splash',
    name: 'Splash',
    component: () => import('@/views/splash/index.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/register/index.vue')
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('@/views/search/index.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/home/index.vue')
  },
  {
    path: '/market',
    name: 'Market',
    component: () => import('@/views/market/index.vue')
  },
  {
    path: '/video',
    name: 'Video',
    component: () => import('@/views/video/index.vue')
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/profile/index.vue')
  },
  {
    path: '/medical',
    name: 'Medical',
    component: () => import('@/views/medical/index.vue')
  },
  {
    path: '/health',
    name: 'Health',
    component: () => import('@/views/health/index.vue')
  },
  {
    path: '/product-listing',
    name: 'ProductListing',
    component: () => import('@/views/product-listing/index.vue')
  },
  // 设置页面
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('@/views/settings/index.vue')
  },
  // 管理员路由
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('@/views/admin/home/index.vue'),
    meta: { requiresAdmin: true },
    children: [
      {
        path: '',
        name: 'AdminDefault',
        redirect: '/admin/home'
      },
      {
        path: 'home',
        name: 'AdminHome',
        component: () => import('@/views/admin/home/index.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  const publicPaths = ['/login', '/register', '/splash']
  

  // 需要认证的页面
  if (!token && !publicPaths.includes(to.path)) {
    next('/login')
    return
  }

  try {
    // 动态获取最新用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    
    // 需要管理员权限的路由
    if (to.matched.some(record => record.meta.requiresAdmin)) {
      if (!userInfo.isAdmin) {
        showToast('权限不足，无法访问')
        next(token ? '/home' : '/login')  // 根据登录状态跳转
        return
      }
    }

    // 可扩展其他权限校验逻辑
    next()
  } catch (e) {
    console.error('路由守卫异常:', e)
    localStorage.clear()
    next('/login')
  }
})

export default router 